# -*- coding: utf-8 -*-
import logging

import cv2
import numpy as np
import pyautogui


def find_x_y(image_path, find_img_path, threshold=0.8):
    """
    使用 OpenCV 进行模板匹配，找到微信图标的位置并返回中心坐标
    :param image_path: 源图像路径
    :param find_img_path: 模板图像路径
    :param threshold: 匹配度阈值
    :return: 微信图标的中心坐标 (x, y)，如果匹配度太低则返回 None
    """
    logging.info(f"find_x_y {image_path} {find_img_path}")
    parent_img = cv2.imread(image_path)
    sub_img = cv2.imread(find_img_path)

    if parent_img is None or sub_img is None:
        raise ValueError("无法加载图像，请检查路径是否正确")

    result = cv2.matchTemplate(parent_img, sub_img, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    # 检查匹配度是否高于阈值
    logging.info(f"匹配度: {max_val} threshold={threshold}")
    if max_val < threshold:
        return 0, 0

    # 获取模板图像的高度和宽度
    h, w = sub_img.shape[:2]

    # 计算中心坐标
    x = int(max_loc[0] + w / 2)
    y = int(max_loc[1] + h / 2)

    return x, y


def capture_region_width_height(x, y, width, height, output_path):
    screenshot = pyautogui.screenshot(region=(x, y, width, height))
    screenshot.save(output_path)
    logging.info(f"capture path {output_path}")


def capture_region_width_height_center(x, y, width, height, output_path):
    left = x - (width // 2)
    top = y - (height // 2)
    # 确保截图区域不超出屏幕
    screen_width, screen_height = pyautogui.size()
    left = max(0, left)
    top = max(0, top)
    right = min(left + width, screen_width)
    bottom = min(top + height, screen_height)
    width = right - left
    height = bottom - top
    screenshot = pyautogui.screenshot(region=(left, top, width, height))
    screenshot.save(output_path)


def capture_region(x1, y1, x2, y2, output_path):
    """
    根据左上角和右下角坐标截图并保存

    :param x1: 左上角 x 坐标
    :param y1: 左上角 y 坐标
    :param x2: 右下角 x 坐标
    :param y2: 右下角 y 坐标
    :param output_path: 截图保存路径
    """
    # 定义截图区域的宽度和高度
    width = x2 - x1
    height = y2 - y1
    # 使用 pyautogui 截图
    screenshot = pyautogui.screenshot(region=(x1, y1, width, height))
    # 保存截图
    screenshot.save(output_path)
    logging.info(f"capture path {output_path}")


def find_x_y_ok(image_path, find_img_path, threshold=0.8):
    x, y = find_x_y(image_path, find_img_path, threshold)
    if x == 0 and y == 0:
        return False
    else:
        logging.info(f"find_x_y ({x}, {y})")
        print(x, y)
        return True


def find_image_position(template_path, x, y, width, height, threshold=0.8, save_path="", position_type="center") -> dict:
    # 1. 加载模板图片(a.png)
    template = cv2.imread(template_path, cv2.IMREAD_COLOR)
    if template is None:
        return {"found": False}
    template_h, template_w = template.shape[:2]
    screenshot = pyautogui.screenshot(region=(x, y, width, height))
    logging.info(f"find_image_position template_path={template_path} save_path={save_path}")
    if len(save_path) > 0:
        screenshot.save(save_path)
    screen = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
    result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    if max_val >= threshold:
        found_x = x + max_loc[0]
        found_y = y + max_loc[1]
        if position_type == "center":
            return_x = found_x + template_w // 2
            return_y = found_y + template_h // 2
        elif position_type == "top_left":
            return_x = found_x
            return_y = found_y
        else:
            raise ValueError("position_type must be 'top_left' or 'center'")
        return {
            "found": True,
            "x": return_x,
            "y": return_y,
            "width": template_w,
            "height": template_h,
            "confidence": max_val
        }
    else:
        return {
            "found": False,
            "confidence": max_val
        }
